/**
 * Description: TCP客户端
 * File: client.c |Time: 2021-07-11 09:44
 */
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <string.h>
#include "trans.h"

int main(int argc, const char *argv[])
{
    if (argc < 3) 
    {
        printf("Usage: %s <ip> <port>", argv[0]);
    }

    int ret = 0;
    msg_t msg;
    int sock_tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_tcp_fd < 0) 
    {
        ERR("socket");
    }

    struct sockaddr_in server_addr;
    socklen_t addrlen = sizeof(server_addr);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);

    ret = connect(sock_tcp_fd, (struct sockaddr *)&server_addr, addrlen);
    if (ret < 0) 
    {
        ERR("connect");
    }

    char *tmp = NULL;

    while(1) {
        printf("[tcp to server]: ");

        memset(&msg, 0, sizeof(msg));
        tmp = fgets(msg.msg, BUFSIZE, stdin);

        ret = send(sock_tcp_fd, &msg, sizeof(msg), 0);
        if (ret < 0) 
        {
            ERR("send");
        }
    }

    ret = close(sock_tcp_fd);
    if (ret < 0) 
    {
        ERR("close");
    }
    
    return 0;
}
